import React, { useState } from 'react';
import {
  Layout,
  Card,
  Button,
  Table,
  Input,
  Select,
  Space,
  Tag,
  Modal,
  message,
  Row,
  Col,
  DatePicker,
  Descriptions
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import './Dashboard.css';

const { Option } = Select;
const { RangePicker } = DatePicker;

// 模拟租户数据
const tenantData = [
  {
    key: '1',
    tenantName: '杭州久策科技有限公司',
    contactPerson: '张三',
    phone: '13800138001',
    email: 'zhangsan@company.com',
    address: '杭州市滨江区江南大道3588号',
    rentArea: '500㎡',
    rentStartDate: '2024-01-01',
    rentEndDate: '2026-12-31',
    monthlyRent: '15000',
    status: '正常',
    createTime: '2024-01-01 10:00:00'
  },
  {
    key: '2',
    tenantName: '杭州融智云科技有限公司',
    contactPerson: '李四',
    phone: '13800138002',
    email: 'lisi@company.com',
    address: '杭州市滨江区江南大道3589号',
    rentArea: '800㎡',
    rentStartDate: '2024-02-01',
    rentEndDate: '2027-01-31',
    monthlyRent: '24000',
    status: '正常',
    createTime: '2024-02-01 10:00:00'
  },
  {
    key: '3',
    tenantName: '杭州智链科技有限公司',
    contactPerson: '王五',
    phone: '13800138003',
    email: 'wangwu@company.com',
    address: '杭州市滨江区江南大道3590号',
    rentArea: '300㎡',
    rentStartDate: '2024-03-01',
    rentEndDate: '2025-02-28',
    monthlyRent: '9000',
    status: '即将到期',
    createTime: '2024-03-01 10:00:00'
  },
  {
    key: '4',
    tenantName: '南宁可达靓成有限公司',
    contactPerson: '赵六',
    phone: '13800138004',
    email: 'zhaoliu@company.com',
    address: '杭州市滨江区江南大道3591号',
    rentArea: '1200㎡',
    rentStartDate: '2024-04-01',
    rentEndDate: '2027-03-31',
    monthlyRent: '36000',
    status: '正常',
    createTime: '2024-04-01 10:00:00'
  },
  {
    key: '5',
    tenantName: '杭州经纬科技有限公司',
    contactPerson: '钱七',
    phone: '13800138005',
    email: 'qianqi@company.com',
    address: '杭州市滨江区江南大道3592号',
    rentArea: '600㎡',
    rentStartDate: '2024-05-01',
    rentEndDate: '2026-04-30',
    monthlyRent: '18000',
    status: '欠费',
    createTime: '2024-05-01 10:00:00'
  }
];

const TenantManage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchForm, setSearchForm] = useState({
    tenantName: '',
    contactPerson: '',
    status: '',
    dateRange: null
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [filteredData, setFilteredData] = useState(tenantData);
  // 详情弹窗状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState(null);

  React.useEffect(() => {
    if (location.state && location.state.newTenant) {
      setFilteredData(prev => [location.state.newTenant, ...prev]);
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  const columns = [
    {
      title: '租户名称',
      dataIndex: 'tenantName',
      key: 'tenantName',
      width: 200,
    },
    {
      title: '联系人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 100,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
    },
    {
      title: '租赁面积',
      dataIndex: 'rentArea',
      key: 'rentArea',
      width: 100,
    },
    {
      title: '月租金',
      dataIndex: 'monthlyRent',
      key: 'monthlyRent',
      width: 100,
      render: (text) => `¥${text}`
    },
    {
      title: '租期',
      key: 'rentPeriod',
      width: 200,
      render: (_, record) => (
        <span>{record.rentStartDate} 至 {record.rentEndDate}</span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        let color = 'green';
        if (status === '即将到期') color = 'orange';
        if (status === '欠费') color = 'red';
        return <Tag color={color}>{status}</Tag>;
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<DeleteOutlined />}
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleSearch = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      const { tenantName, contactPerson, status, dateRange } = searchForm;
      setFilteredData(
        tenantData.filter(item => {
          const matchTenant = tenantName ? item.tenantName.includes(tenantName) : false;
          const matchContact = contactPerson ? item.contactPerson.includes(contactPerson) : false;
          const matchStatus = status ? item.status === status : false;
          let matchDate = false;
          if (dateRange && dateRange.length === 2) {
            const start = dateRange[0].startOf('day');
            const end = dateRange[1].endOf('day');
            const create = window.dayjs(item.createTime);
            matchDate = create.isBetween(start, end, null, '[]');
          }
          return matchTenant || matchContact || matchStatus || matchDate;
        })
      );
      message.success('搜索完成');
    }, 1000);
  };

  const handleReset = () => {
    setSearchForm({
      tenantName: '',
      contactPerson: '',
      status: '',
      dateRange: null
    });
  };

  const handleAdd = () => {
    navigate('/tenant/create');
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的租户');
      return;
    }
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个租户吗？`,
      onOk() {
        message.success('删除成功');
        setSelectedRowKeys([]);
      },
    });
  };

  const handleView = (record) => {
    setCurrentDetail(record);
    setDetailVisible(true);
  };

  const handleEdit = (record) => {
    message.info(`编辑租户：${record.tenantName}`);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除租户"${record.tenantName}"吗？`,
      onOk() {
        // 删除filteredData中的对应项
        setFilteredData(prev => prev.filter(item => item.key !== record.key));
        message.success('删除成功');
      },
    });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  return (
    <Layout className="dashboard-root">
      <div style={{ padding: '24px', background: '#f5f7fa', minHeight: '100vh' }}>
        <Card>
          {/* 返回按钮 */}
          <div style={{ marginBottom: 16 }}>
            <Button
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/dashboard/enterprise')}
              style={{ marginBottom: 16 }}
            >
              返回
            </Button>
          </div>

          {/* 页面标题 */}
          <div style={{ marginBottom: 24 }}>
            <h2 style={{ margin: 0, color: '#1f1f1f' }}>租户信息管理</h2>
          </div>

          {/* 搜索区域 */}
          <Card style={{ marginBottom: 16, background: '#fafafa' }}>
            <Row gutter={16}>
              <Col span={6}>
                <div style={{ marginBottom: 8 }}>
                  <label style={{ color: '#666' }}>租户名称：</label>
                </div>
                <Input
                  placeholder="请输入租户名称"
                  value={searchForm.tenantName}
                  onChange={(e) => setSearchForm({ ...searchForm, tenantName: e.target.value })}
                />
              </Col>
              <Col span={6}>
                <div style={{ marginBottom: 8 }}>
                  <label style={{ color: '#666' }}>联系人：</label>
                </div>
                <Input
                  placeholder="请输入联系人"
                  value={searchForm.contactPerson}
                  onChange={(e) => setSearchForm({ ...searchForm, contactPerson: e.target.value })}
                />
              </Col>
              <Col span={6}>
                <div style={{ marginBottom: 8 }}>
                  <label style={{ color: '#666' }}>状态：</label>
                </div>
                <Select
                  placeholder="请选择状态"
                  style={{ width: '100%' }}
                  value={searchForm.status}
                  onChange={(value) => setSearchForm({ ...searchForm, status: value })}
                  allowClear
                >
                  <Option value="正常">正常</Option>
                  <Option value="即将到期">即将到期</Option>
                  <Option value="欠费">欠费</Option>
                </Select>
              </Col>
              <Col span={6}>
                <div style={{ marginBottom: 8 }}>
                  <label style={{ color: '#666' }}>创建时间：</label>
                </div>
                <RangePicker
                  style={{ width: '100%' }}
                  value={searchForm.dateRange}
                  onChange={(dates) => setSearchForm({ ...searchForm, dateRange: dates })}
                />
              </Col>
            </Row>
            <Row style={{ marginTop: 16 }}>
              <Col span={24}>
                <Space>
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={handleSearch}
                    loading={loading}
                  >
                    查询
                  </Button>
                  <Button onClick={handleReset}>重置</Button>
                </Space>
              </Col>
            </Row>
          </Card>

          {/* 操作按钮 */}
          <div style={{ marginBottom: 16 }}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                新增租户
              </Button>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
              >
                批量删除
              </Button>
            </Space>
          </div>

          {/* 表格 */}
          <Table
            columns={columns}
            dataSource={filteredData}
            rowSelection={rowSelection}
            loading={loading}
            pagination={false}
            bordered
            style={{ background: '#fff', marginTop: 16 }}
          />
          {/* 详情弹窗 */}
          <Modal
            open={detailVisible}
            title="租户详情"
            footer={null}
            onCancel={() => setDetailVisible(false)}
            width={600}
          >
            {currentDetail && (
              <Descriptions column={1} bordered size="middle">
                <Descriptions.Item label="租户名称">{currentDetail.tenantName}</Descriptions.Item>
                <Descriptions.Item label="联系人">{currentDetail.contactPerson}</Descriptions.Item>
                <Descriptions.Item label="联系电话">{currentDetail.phone}</Descriptions.Item>
                <Descriptions.Item label="邮箱">{currentDetail.email}</Descriptions.Item>
                <Descriptions.Item label="地址">{currentDetail.address}</Descriptions.Item>
                <Descriptions.Item label="租赁面积">{currentDetail.rentArea}</Descriptions.Item>
                <Descriptions.Item label="月租金">¥{currentDetail.monthlyRent}</Descriptions.Item>
                <Descriptions.Item label="租期">{currentDetail.rentStartDate} 至 {currentDetail.rentEndDate}</Descriptions.Item>
                <Descriptions.Item label="状态">{currentDetail.status}</Descriptions.Item>
                <Descriptions.Item label="创建时间">{currentDetail.createTime}</Descriptions.Item>
              </Descriptions>
            )}
          </Modal>
        </Card>
      </div>
    </Layout>
  );
};

export default TenantManage; 